'use client';

import { useEffect, useState } from 'react';
import { useAIHealth } from '@/lib/hooks/useAI';

interface AIHealthStatusProps {
  className?: string;
}

export function AIHealthStatus({ className = "" }: AIHealthStatusProps) {
  const { health, checkHealth, loading } = useAIHealth();
  const [lastChecked, setLastChecked] = useState<Date | null>(null);

  useEffect(() => {
    checkHealth().then(() => {
      setLastChecked(new Date());
    });
  }, [checkHealth]);

  const getStatusColor = (status: boolean) => {
    return status ? 'text-emerald-600' : 'text-red-500';
  };

  const getStatusIcon = (status: boolean) => {
    return status ? (
      <div className="w-2 h-2 bg-emerald-500 rounded-full animate-pulse" />
    ) : (
      <div className="w-2 h-2 bg-red-500 rounded-full" />
    );
  };

  if (loading && !health) {
    return (
      <div className={`flex items-center gap-2 px-3 py-1.5 bg-gray-50 rounded-lg ${className}`}>
        <div className="w-3 h-3 border-2 border-gray-300 border-t-blue-500 rounded-full animate-spin" />
        <span className="text-xs font-medium text-gray-600">Checking service status...</span>
      </div>
    );
  }

  if (!health) {
    return (
      <div className={`flex items-center gap-2 px-3 py-1.5 bg-gray-50 rounded-lg ${className}`}>
        <div className="w-2 h-2 bg-gray-400 rounded-full" />
        <span className="text-xs font-medium text-gray-600">Service status unknown</span>
      </div>
    );
  }

  const allServices = [
    { key: 'qwen', label: 'AI Chat', status: health.qwen },
    { key: 'elevenlabs', label: 'Speech Synthesis', status: health.elevenlabs },
    { key: 'deepgram', label: 'Speech Recognition', status: health.deepgram }
  ];

  const allHealthy = allServices.every(service => service.status);

  return (
    <div className={`flex items-center gap-2 px-3 py-1.5 bg-white border border-gray-200 rounded-lg shadow-sm ${className}`}>
      <div className="flex items-center gap-1">
        <div className={`w-2 h-2 rounded-full ${allHealthy ? 'bg-emerald-500 animate-pulse' : 'bg-red-500'}`} />
        <span className="text-xs font-medium text-gray-700">AI Services</span>
      </div>
      
      <div className="flex items-center gap-3">
        {allServices.map((service, index) => (
          <div key={service.key} className="flex items-center gap-1">
            {getStatusIcon(service.status)}
            <span className={`text-xs font-medium ${getStatusColor(service.status)}`}>
              {service.label}
            </span>
            {index < allServices.length - 1 && (
              <div className="w-0.5 h-3 bg-gray-200" />
            )}
          </div>
        ))}
      </div>
      
      {lastChecked && (
        <div className="text-xs text-gray-400 ml-2 pl-2 border-l border-gray-200">
          {lastChecked.toLocaleTimeString('en-US', { 
            hour: '2-digit', 
            minute: '2-digit' 
          })}
        </div>
      )}
    </div>
  );
}